package com.domain.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.domain.common.Const;
import com.domain.common.Result;
import com.domain.dao.*;
import com.domain.pojo.*;
import com.domain.service.PushMessageService;
import com.domain.utils.NotNullUtils;
import com.domain.utils.UUIDUtils;
import com.domain.utils.jiguang.Jdpush;
import com.domain.utils.wyyx.IMSndmsg;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PushMessageServiceImpl implements PushMessageService {
    @Autowired
    private PushMessageMapper pushMessageMapper;

    @Autowired
    private UsersMapper usersMapper;


    @Autowired
    private PublishAcceptanceMapper publishAcceptanceMapper;

    @Autowired
    private UsersGroupInfoMapper usersGroupInfoMapper;


    /**
     * 获取用户推送列表
     *
     * @param userId
     * @return
     */
    @Override
    public Result getPushMessageList(String userId, String pushType, String pageNum, String pageSize) {
        PageHelper.startPage(new Integer(pageNum), new Integer(20));
        List<PushMessage> pushMessages = pushMessageMapper.selectByUsersId(userId, pushType);
        PageInfo pageInfo = new PageInfo(pushMessages);
        return Result.success("操作成功", pageInfo.getList());
    }

    /**
     * 添加推送帮忙消息
     *
     * @param pushUsersId     被推送者id
     * @param pushUsersSendId 推送者id
     * @param pushContent     推送消息
     * @param pushTitle       推送标题
     * @param spareOne        推送备用信息
     * @param spare_three     推送小分类
     * @param pushId          推送id
     * @return
     */
    @Override
    public Result addPublishiMessage(String pushUsersId, String pushUsersSendId, String pushContent, String pushTitle, String spareOne, String spare_three, String pushId) {
        //添加帮忙消息
        PushMessage pe = new PushMessage();
        pe.setId(pushId);
        pe.setPushTitle(pushTitle);
        pe.setSpareOne(spareOne);
        pe.setPushContent(pushContent);
        pe.setCreatTime(new Date());
        pe.setPushUsersSendId(pushUsersSendId);
        pe.setPushUsersId(pushUsersId);
        pe.setPushType(Const.PUBLISH_MESSAGE);
        pe.setSpareTwo(Const.MESSAGE_STATE);
        pe.setSpareThree(spare_three);
        pushMessageMapper.insertSelective(pe);
        return Result.success();
    }

    /**
     * 添加推送系统消息
     *
     * @param pushUsersId
     * @param pushUsersSendId
     * @param pushContent
     * @param pushTitle
     * @param spareOne
     * @return
     */
    @Override
    public Result addSystemMessage(String pushUsersId, String pushUsersSendId, String pushContent, String pushTitle, String spareOne, String spareThree, String pushId) {
        //添加系统消息
        PushMessage pe = new PushMessage();
        pe.setId(pushId);
        pe.setPushTitle(pushTitle);
        pe.setSpareOne(spareOne);
        pe.setPushContent(pushContent);
        pe.setCreatTime(new Date());
        pe.setPushUsersSendId(pushUsersSendId);
        pe.setPushUsersId(pushUsersId);
        pe.setPushType(Const.SYSTEM_MESSAGE);
        pe.setSpareTwo(Const.MESSAGE_STATE);
        pe.setSpareThree(spareThree);
        pushMessageMapper.insertSelective(pe);
        return Result.success();
    }

    /**
     * 添加答谢通知
     *
     * @param pushUsersId
     * @param pushUsersSendId
     * @param pushContent
     * @param pushTitle
     * @param spareOne
     * @param spare_three
     * @param pushId
     * @return
     */
    @Override
    public Result addAcknowledgeMessage(String pushUsersId, String pushUsersSendId, String pushContent, String pushTitle, String spareOne, String spare_three, String pushId) {
        //添加答谢通知
        PushMessage pe = new PushMessage();
        pe.setId(pushId);
        pe.setPushTitle(pushTitle);
        pe.setSpareOne(spareOne);
        pe.setPushContent(pushContent);
        pe.setCreatTime(new Date());
        pe.setPushUsersSendId(pushUsersSendId);
        pe.setPushUsersId(pushUsersId);
        pe.setPushType(Const.THANK_MESSAGE);
        pe.setSpareTwo(Const.MESSAGE_STATE);
        pe.setSpareThree(spare_three);
        pushMessageMapper.insertSelective(pe);
        return Result.success();
    }

    /**
     * 已读
     *
     * @param messageId
     * @return
     */
    @Override
    public Result changePushMessageState(String messageId) {
        PushMessage pe = new PushMessage();
        pe.setId(messageId);
        pe.setSpareTwo(Const.MESSAGE_STATE_YES);
        pe.setUpdateTime(new Date());
        pushMessageMapper.updateByPrimaryKeySelective(pe);
        return Result.success();
    }

    /**
     * 受理推送消息详情
     *
     * @param pushMessageId
     * @param pushType
     * @param pushTypes     @return
     */
    @Override
    public Result acceptancePushDetail(String pushMessageId, String pushType, String pushTypes) {
        Map<String, Object> maps = new HashMap<>();
        //获取推送详情
        PushMessage pe = pushMessageMapper.selectByPrimaryKey(pushMessageId);
        //获取受理人详情
        Users users = usersMapper.selectByPrimaryKey(pe.getPushUsersSendId());
        //获取帮转详情
        PublishAcceptance publishAcceptance = publishAcceptanceMapper.selectByPrimaryKey(pe.getSpareOne());
        //获取
        if (NotNullUtils.isNotNullObject(users)) {
            //受理人信息
            maps.put("usersInfo", users);
            //发布信息
            maps.put("publishId", publishAcceptance.getPublishId());
            //受理留言
            maps.put("acceptanceContent", publishAcceptance.getAcceptanceMessage());
            //人脉链关系列表 TODO
            maps.put("humanChain", publishAcceptance.getAcceptanceMessage());
        }
        return Result.success("操作成功", maps);
    }

    /**
     * 创建讨论组
     *
     * @param usersId   用户id
     * @param friendsId 人脉id(json 数组)
     * @param accpId    受理人id
     * @param publishId 发布id
     * @return
     */
    @Override
    public Result creatGroup(String usersId, String friendsId, String accpId, String publishId) throws IOException {
        //发布者信息
        Users user = usersMapper.selectByPrimaryKey(usersId);
        //受理者信息
        Users useraccp = usersMapper.selectByPrimaryKey(accpId);
        //创建群时（群名称）
        String teamName = "" + user.getName() + "的帮忙讨论组";
        //创建群聊时默认将受理人拉入群
        String members = "['" + accpId + "']";
        //拉人入群时的信息
        String msg = "{'msg':''}";
        String result = IMSndmsg.createTeam(teamName, user.getId(), members, "", "", msg, "0", "0", "1", "0", "0");
        //创建群成功
        JSONObject jsObject = JSONObject.parseObject(result);
        if (jsObject.get("code").equals(200)) {
            //添加创建群信息
            UsersGroupInfo uf = new UsersGroupInfo();
            uf.setUsersId(usersId);
            uf.setGroupId(jsObject.get("tid").toString());
            uf.setCreatTime(new Date());
            uf.setGroupName(teamName);
            uf.setId(UUIDUtils.getRandomUUID());
            uf.setPublishId(publishId);
            uf.setSpareOne(accpId);
            usersGroupInfoMapper.insertSelective(uf);
            //创建群成功（通知人脉链进群）
            JSONArray jsonArray = JSONArray.parseArray(friendsId);
            Object[] objects = jsonArray.toArray();
            for (int i = 0; i < objects.length; i++) {
                //推送中间人脉链进群
                String friendsIds = (String) objects[i];
                //推送消息id
                String pushId = UUIDUtils.getRandomUUID();
                int results = Jdpush.sendToAliasList(friendsIds, "" + useraccp.getName() + "接受了您人脉链中" + user.getName() + "的求助信息", pushId, Const.join_group, "邀请加入讨论组");
                if (results == 1) {
                    //添加推送记录
                    addPublishiMessage(friendsId, accpId, "" + useraccp.getName() + "接受了您人脉链中" + user.getName() + "的求助信息,赶快加入讨论组帮助他们吧", "邀请加入讨论组", publishId, Const.join_group, pushId);
                }
            }
        }
        return Result.success(result);
    }

    /**
     * 获取邀请加入讨论组详情
     *
     * @param pushMessageId
     * @param pushType
     * @return
     */
    @Override
    public Result getJoinGroupDetail(String pushMessageId, String pushType) {
        Map<String, Object> maps = new HashMap<>();
        //获取推送消息详情
        PushMessage pe = pushMessageMapper.selectByPrimaryKey(pushMessageId);
        //获取邀请人详情
        Users users = usersMapper.selectByPrimaryKey(pe.getPushUsersId());
        maps.put("usersInfo", users);
        //人脉关系链 todo
        maps.put("", "");
        //推送详情
        maps.put("pushContent", pe.getPushContent());
        maps.put("publishId", pe.getSpareOne());
        return Result.success("操作成功", maps);
    }
}
